#include "OwnQTabWidget.h"

namespace SQLDoc
{
	OwnQTabWidget::OwnQTabWidget(QWidget *parent)
		: QTabWidget(parent)
	{
		tabBar()->installEventFilter(this);

		/* Tab close button */
		QToolButton *closeTabButton = new QToolButton(this);
		this->setCornerWidget(closeTabButton, Qt::TopRightCorner);
		closeTabButton->setCursor(Qt::ArrowCursor);
		closeTabButton->setAutoRaise(true);
		closeTabButton->setIcon(QIcon(QString::fromUtf8(":/ico/closetab_ico16.png")));
		closeTabButton->setToolTip(tr("Close page"));
		closeTabButton->setEnabled(this->count() > 0);

		connect(closeTabButton, SIGNAL(clicked(void)), this, SLOT(closeTab_clicked(void)));
	}

	bool OwnQTabWidget::eventFilter(QObject *o, QEvent *e)
	{
		if (o == tabBar() && e->type() == QEvent::MouseButtonPress) {
			QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(e);
			if (mouseEvent->button() == Qt::MidButton)
			{
				emit tabsChanged(this->count());
				removeTab(tabBar()->tabAt(mouseEvent->pos()));
				return true;
			}
		}
		return QTabWidget::eventFilter(o, e);
	}

	void OwnQTabWidget::closeTab_clicked(void)
	{
		if(this->count() < 1)
			return;

		QWidget *current = this->currentWidget();
		this->removeTab(this->indexOf(current));

		emit tabsChanged(this->count());

		if (current != m_startPage)
			delete current;
	}

	QWidget *OwnQTabWidget::addNewTab(DBTable *table)
	{
		/* Documentation says page widget should not have parent so NULL */
		TableViewGadget *tab = new TableViewGadget();
		tab->setTable(table);

		addTab(tab, table->name());
		setCurrentWidget(tab);

		emit tabsChanged(this->count());

		return tab;
	}

	QWidget *OwnQTabWidget::startPage(void)
	{
		return this->m_startPage;
	}

	void OwnQTabWidget::setStartPage(QWidget *widget)
	{
		this->m_startPage = widget;
	}

	void OwnQTabWidget::showStartPage()
	{
		if (m_startPage)
		{
			this->addTab(m_startPage, "Start Page");
			this->setCurrentWidget(m_startPage);

			emit tabsChanged(this->count());
		}
	}
}
